import { useEffect, useState } from 'react';
import axios from 'axios';
import { useTheme } from '../context/ThemeContext';
import DashboardLayout from '../components/DashboardLayout';
import AskFormView from '../components/AskFormView';
import AskFormEdit from '../components/AskFormEdit';
import ReplyFormView from '../components/ReplyFormView';
import TabButtons from '../components/TabButtons';
import { AskForm } from '../types/forms';

const AskerDashboard: React.FC = () => {
    const { theme } = useTheme();
    const [askForms, setAskForms] = useState<AskForm[]>([]);
    const [selectedForm, setSelectedForm] = useState<AskForm | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [isEditing, setIsEditing] = useState(false);
    const [activeTab, setActiveTab] = useState<'unanswered' | 'answered'>('unanswered');
    const [editingForm, setEditingForm] = useState<Partial<AskForm>>({
        submitter: '',
        company: '',
        department: '',
        position: '',
        isInternalAuditor: false,
        question: '',
    });
    const [currentUserId, setCurrentUserId] = useState('');

    useEffect(() => {
        const fetchAskForms = async () => {
            try {
                const token = localStorage.getItem('token');
                const response = await axios.get('http://localhost:8000/api/askforms/my', {
                    headers: { Authorization: `Bearer ${token}` },
                    params: { userId: currentUserId }
                });
                setAskForms(response.data);
                setLoading(false);
            } catch (err) {
                setError('获取表单失败');
                setLoading(false);
            }
        };

        if (currentUserId) {
            fetchAskForms();
        }
    }, [currentUserId]);

    useEffect(() => {
        const userId = localStorage.getItem('userId') || '';
        const username = localStorage.getItem('username') || '';
        setCurrentUserId(userId);
        setEditingForm(prev => ({
            ...prev,
            submitter: username,
            submitterUserId: userId
        }));
    }, []);

    const handleAddForm = () => {
        setIsEditing(true);
        setSelectedForm(null);
        setEditingForm({
            submitter: localStorage.getItem('username') || '',
            submitterUserId: currentUserId,
            company: '',
            department: '',
            position: '',
            isInternalAuditor: false,
            question: '',
        });
    };

    const handleEditForm = (form: AskForm) => {
        setIsEditing(true);
        setEditingForm(form);
    };

    const handleSubmitForm = async () => {
        if (!window.confirm('确定要提交这个表单吗？')) return;
        try {
            const token = localStorage.getItem('token');
            const method = editingForm.id ? 'put' : 'post';
            const url = editingForm.id 
                ? `http://localhost:8000/api/askforms/${editingForm.id}`
                : 'http://localhost:8000/api/askforms';

            await axios[method](url, {
                ...editingForm,
                submitterUserId: currentUserId,
            }, {
                headers: { Authorization: `Bearer ${token}` },
            });

            setIsEditing(false);
            setEditingForm({
                submitter: '',
                company: '',
                department: '',
                position: '',
                isInternalAuditor: false,
                question: '',
            });

            // 刷新表单列表
            const response = await axios.get('http://localhost:8000/api/askforms/my', {
                headers: { Authorization: `Bearer ${token}` },
                params: { userId: currentUserId }
            });
            setAskForms(response.data);
            setActiveTab('unanswered');
        } catch (err) {
            setError(editingForm.id ? '更新表单失败' : '添加表单失败');
        }
    };

    const handleCancel = () => {
        setIsEditing(false);
        setEditingForm({
            submitter: '',
            company: '',
            department: '',
            position: '',
            isInternalAuditor: false,
            question: '',
        });
    };

    const handleDeleteForm = async (id: number) => {
        if (!window.confirm('确定要删除这个表单吗？')) return;
        try {
            const token = localStorage.getItem('token');
            await axios.delete(`http://localhost:8000/api/askforms/${id}`, {
                headers: { Authorization: `Bearer ${token}` },
            });
            const response = await axios.get('http://localhost:8000/api/askforms/my', {
                headers: { Authorization: `Bearer ${token}` },
                params: { userId: currentUserId }
            });
            setAskForms(response.data);
            if (selectedForm?.id === id) {
                setSelectedForm(null);
            }
        } catch (err) {
            setError('删除表单失败');
        }
    };

    const renderFormList = () => {
        const filteredForms = askForms.filter(form => 
            activeTab === 'answered' ? form.isAnswered : !form.isAnswered
        );
        return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                {filteredForms.map((form) => (
                    <div
                        key={form.id}
                        onClick={() => setSelectedForm(form)}
                        style={{
                            padding: '15px',
                            border: '1px solid #ddd',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            backgroundColor: selectedForm?.id === form.id 
                                ? (theme === 'light' ? '#e3f2fd' : '#2c3e50')
                                : (theme === 'light' ? 'white' : '#495057'),
                        }}
                    >
                        <div style={{ fontWeight: 'bold', marginBottom: '5px' }}>
                            {form.department} - {form.position}
                        </div>
                        <div style={{ 
                            fontSize: '0.9em', 
                            color: theme === 'light' ? '#666' : '#ccc',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis'
                        }}>
                            {form.question}
                        </div>
                        <div style={{
                            fontSize: '0.8em',
                            color: theme === 'light' ? '#888' : '#aaa',
                            marginTop: '5px'
                        }}>
                            状态: {form.isAnswered ? '已回复' : '未回复'}
                        </div>
                    </div>
                ))}
            </div>
        );
    };

    const sidebarContent = (
        <>
            <h2 style={{ marginBottom: '20px' }}>我的提问</h2>
            <button 
                onClick={handleAddForm}
                style={{
                    padding: '10px',
                    backgroundColor: '#28a745',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    marginBottom: '20px',
                    width: '100%'
                }}
            >
                添加新表单
            </button>
            <TabButtons
                options={[
                    { 
                        key: 'unanswered', 
                        label: '未回复', 
                        count: askForms.filter(form => !form.isAnswered).length 
                    },
                    { 
                        key: 'answered', 
                        label: '已回复', 
                        count: askForms.filter(form => form.isAnswered).length 
                    }
                ]}
                activeTab={activeTab}
                onChange={(key) => setActiveTab(key as 'unanswered' | 'answered')}
            />
            {loading ? (
                <p>加载中...</p>
            ) : error ? (
                <p style={{ color: 'red' }}>{error}</p>
            ) : (
                renderFormList()
            )}
        </>
    );

    const mainContent = (
        <div style={{ maxWidth: '800px', margin: '0 auto', position: 'relative', minHeight: '100%' }}>
            {isEditing ? (
                <>
                    <h2 style={{ marginBottom: '30px' }}>
                        {editingForm.id ? '更新表单' : '添加新表单'}
                    </h2>
                    <div style={{ 
                        backgroundColor: theme === 'light' ? 'white' : '#495057',
                        padding: '20px',
                        borderRadius: '8px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                        <AskFormEdit
                            form={editingForm}
                            onChange={setEditingForm}
                            onSubmit={handleSubmitForm}
                            onCancel={handleCancel}
                            submitLabel={editingForm.id ? '更新' : '提交'}
                        />
                    </div>
                </>
            ) : selectedForm ? (
                <>
                    <h2 style={{ marginBottom: '30px' }}>问题详情</h2>
                    <div style={{ 
                        backgroundColor: theme === 'light' ? 'white' : '#495057',
                        padding: '20px',
                        borderRadius: '8px',
                        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                        <AskFormView 
                            form={selectedForm}
                            onEdit={() => handleEditForm(selectedForm)}
                            onDelete={() => handleDeleteForm(selectedForm.id)}
                            canEdit={!selectedForm.isAnswered}
                        />
                        {selectedForm.replies && selectedForm.replies[0] && (
                            <div style={{ marginTop: '20px' }}>
                                <ReplyFormView 
                                    reply={selectedForm.replies[0]}
                                    canEdit={false}
                                />
                            </div>
                        )}
                    </div>
                </>
            ) : (
                <div style={{ 
                    height: '100%', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center',
                    color: theme === 'light' ? '#666' : '#ccc'
                }}>
                    <p>请选择左侧的问题查看详情</p>
                </div>
            )}
        </div>
    );

    return (
        <DashboardLayout sidebarContent={sidebarContent}>
            {mainContent}
        </DashboardLayout>
    );
};

export default AskerDashboard; 